package com.hixtrip.sample.app.service;

import com.hixtrip.sample.app.api.OrderService;
import com.hixtrip.sample.app.convertor.OrderConvertor;
import com.hixtrip.sample.client.common.R;
import com.hixtrip.sample.client.order.dto.CommandOderCreateDTO;
import com.hixtrip.sample.client.order.dto.CommandPayDTO;
import com.hixtrip.sample.domain.commodity.CommodityDomainService;
import com.hixtrip.sample.domain.inventory.InventoryDomainService;
import com.hixtrip.sample.domain.order.OrderDomainService;
import com.hixtrip.sample.domain.order.model.Order;
import com.hixtrip.sample.domain.pay.model.CommandPay;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Random;

/**
 * app层负责处理request请求，调用领域服务
 */
@Component
public class OrderServiceImpl implements OrderService {
    @Resource
    private InventoryDomainService inventoryDomainService;
    @Resource
    private CommodityDomainService commodityDomainService;
    @Resource
    private OrderDomainService orderDomainService;
    @Override
    public R<Void> createOrder(CommandOderCreateDTO commandOderCreateDTO) {
        String skuId = commandOderCreateDTO.getSkuId();

        boolean result = inventoryDomainService.reservePreemptively(skuId, commandOderCreateDTO.getAmount().longValue());
        if(!result){
            //库存不足
            return R.error("库存不足");
        }

        BigDecimal moneySum = commodityDomainService.getSkuPrice(skuId).multiply(new BigDecimal(commandOderCreateDTO.getAmount()));

        Order order = OrderConvertor.OrderBuild(commandOderCreateDTO, moneySum);
        orderDomainService.createOrder(order);
        //返回支付信息xxx
        return R.success();
    }
    /**
     * 判断是否重复支付方式：1.创建订单的时候将订单号保存到redis中，第三方支付成功回调用拿到订单编号lua脚本查询并删除，如果call(key)的时候不到就是是重复支付订单
     */
    @Override
    public R<Void> payOk(CommandPayDTO commandPayDTO) {
//        CommandPay commandPay = OrderConvertor.INSTANCE.commandPayBuildByDTO(commandPayDTO);

        CommandPay commandPay = OrderConvertor.commandPayBuildByDTO(commandPayDTO);
        orderDomainService.orderPaySuccess(commandPay);
        //日志重试xxxxx
        return R.success();
    }

    @Override
    public R<Void> payERROR(CommandPayDTO commandPayDTO) {
//        CommandPay commandPay = OrderConvertor.INSTANCE.commandPayBuildByDTO(commandPayDTO);
        CommandPay commandPay = OrderConvertor.commandPayBuildByDTO(commandPayDTO);
        orderDomainService.orderPayFail(commandPay);
        return R.error("支付失败");

    }


    /*
        模拟订单号
     */

}
